from machine import Pin, ADC, PWM
import time

# 设置BUZZER引脚和PWM频率
buzzer_pin = Pin(7)
buzzer_pwm = PWM(buzzer_pin)

led_pin = Pin(6, Pin.OUT)
button_pin = Pin(0, Pin.IN, Pin.PULL_UP)
ldr_pin = ADC(28)

# 设置阈值，根据实际情况调整
threshold = 200

# 设置阈值，根据实际情况调整
mic_threshold = 0.5

# 定义不同按键触发的音符频率
freq_map = {
    1: 262,
    2: 294,
    3: 330,
    4: 349,
    5: 392,
    6: 440,
    7: 494,
}

# 定义单个音符的时长
duration = 0.5

# 播放单个音符
def play_single_note_by_num(num):
    freq = freq_map[num]
    if freq > 0:
        buzzer_pwm.freq(freq)
        buzzer_pwm.duty_u16(16384)
        led_pin.value(1)
        time.sleep(duration)
        buzzer_pwm.duty_u16(0)
        led_pin.value(0)
        time.sleep(0.1)


def loop_light(tone):
    global threshold, last_play_time
    # 获取光敏电阻的模拟值
    ldr_value = ldr_pin.read_u16()
    
    # 输出光敏电阻模拟值到控制台
    # print("LDR analog value: %s" % ldr_value )
    
    # 如果光线的变化大于阈值，并且已经过了复位时间，则点亮LED并播放音符
    if  threshold - ldr_value > 500 :#and threshold == 65535:
        print( "dingdong" )
        play_single_note_by_num(tone)

    threshold = ldr_value
    
def loop_mic(tone):

    # 获取声音模拟值
    mic_pin = ADC(29)
    mic_value = mic_pin.read_u16() / 65535
    
    # 输出声音模拟值到控制台
    print("Mic analog value: %s" % mic_value)
    
    # 如果声音的变化大于阈值，则点亮LED并播放音符5
    if mic_value >= mic_threshold:
        play_single_note_by_num(tone)
        
while True:
    
    loop_mic(5)
    loop_light(6)
    
    time.sleep(0.1)